package com.mobiporter.adias.tags;

import imager.imageresizer.Converter;
import imager.imageresizer.ImageFormatNotFound;
import imager.imageresizer.ImageRenderingException;
import imager.imageresizer.ImageWrapper;
import imager.imageresizer.ImageServerTag.ServerResize;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import net.sourceforge.wurfl.wall.TagUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * A tag to render a picture
 * 
 * @author Chetan Kumar
 *
 */
public class Picture extends MobiTag {

	private static Log log = LogFactory.getLog(ServerResize.class);
	private static final long serialVersionUID = 1L;
	HttpServletRequest request = null;
	HttpServletResponse response = null;

	//  locals
	String warning = "";
	String UA = "";
	String device_id = "";
	String capability_value = "";
	boolean showDefault = false;
	//    String DEFAULT_IMAGE=pageContext.getServletContext()+"\\arbit.jpg";
	String DEFAULT_IMAGE = "\\arbit.jpg";
	String ALT = "image";
	String finalImage = "";
	//    attributes
	String imageSource = "";
	String remoteImage = "";
	String factor = "";
	String format = "";
	String remoteRefresh = "";
	String alt = "";
	String defaultImageLocation = "";
	String fixedSize = "";

	public String getAlt() {
		return alt;
	}

	public String getDefaultImageLocation() {
		return defaultImageLocation;
	}

	public String getFactor() {
		return factor;
	}

	public String getFormat() {
		return format;
	}

	

	public String getImageSource() {
		return imageSource;
	}

	public String getRemoteImage() {
		return remoteImage;
	}

	

	public String getRemoteRefresh() {
		return remoteRefresh;
	}

	public void setDefaultImageLocation(String defaultImageLocation) {
		this.defaultImageLocation = defaultImageLocation;
	}

	public void setFactor(String factor) {
		this.factor = factor;
	}

	public void setFormat(String format) {
		this.format = format;
	}


	public void setImageSource(String imageSource) {
		this.imageSource = imageSource;
	}

	public void setRemoteImage(String remoteImage) {
		this.remoteImage = remoteImage;
	}

	public void setRemoteRefresh(String remoteRefresh) {
		this.remoteRefresh = remoteRefresh;
	}

	public void setAlt(String alt) {
		this.alt = alt;
	}

	public String getFinalImagePath(String currentServletPath,
			String finalImagePath) {
		String returnString = finalImagePath;
		int contextDepth = StringUtils.countMatches(currentServletPath, "/");

		contextDepth--;

		for (; contextDepth > 0; contextDepth--) {
			returnString = "../" + returnString;
		}

		return returnString;
	}

	public String getImageSourcePathFromTheAppBase(String currentServletPath,
			String sourceImagePath) {
		String returnImagePath = sourceImagePath;
		String imageContextPathFromAppBase = currentServletPath;
		int contextDepth = StringUtils.countMatches(sourceImagePath, "../");
		log.debug("CurrentServletPath " + currentServletPath
				+ ": source Image :" + sourceImagePath + ":::count "
				+ contextDepth);
		if (contextDepth > 0) {
			//try extracting the imageFileName so as to we can have a path from the appBase.
			returnImagePath = sourceImagePath;//../images/simbad

			try {
				imageContextPathFromAppBase = imageContextPathFromAppBase
						.substring(0, imageContextPathFromAppBase
								.lastIndexOf("/"));
				log.debug("#### " + imageContextPathFromAppBase);
			} catch (StringIndexOutOfBoundsException e) {
				//Do Nothing
			}

			returnImagePath = returnImagePath.substring(returnImagePath
					.lastIndexOf("../") + 3);

			for (; contextDepth > 0; contextDepth--) {
				imageContextPathFromAppBase = StringUtils.substring(
						imageContextPathFromAppBase, 0,
						imageContextPathFromAppBase.lastIndexOf("/"));
			}
			log.debug("imageContextPathFromAppBase: "
					+ imageContextPathFromAppBase);
			//now club the path..
			returnImagePath = imageContextPathFromAppBase + "/"
					+ returnImagePath;
		} else {

			try {
				imageContextPathFromAppBase = imageContextPathFromAppBase
						.substring(0, imageContextPathFromAppBase
								.lastIndexOf("/"));
				//				log.debug("ADA adfas "+imageContextPathFromAppBase);
			} catch (StringIndexOutOfBoundsException e) {
				//Do Nothing
			}
			//Now just append the path 
			returnImagePath = imageContextPathFromAppBase + "/"
					+ returnImagePath;
			return returnImagePath;

		}
		log.debug("^^^^^^^FInal return Path..." + returnImagePath);
		return returnImagePath;
	}

	public int doStartTag() throws JspException {

		//validation of what's requested.. 

		/**valid combination.. imgSrc +
		 * 1. factor
		 * 2. height . width
		 * 3. format . +1/2 
		 * 4. remoteImg(true) +1/2 +[3]
		 */

		float factor = -1;
		int height = -1;
		int width = -1;
		boolean remoteRefresh = false;
		if (getFactor() != null && !getFactor().equalsIgnoreCase("")) {
			factor = Float.parseFloat(getFactor());
		}

		

		if (getRemoteRefresh() != null
				&& !getRemoteRefresh().equalsIgnoreCase("")) {
			if (getRemoteRefresh().equalsIgnoreCase("yes")
					|| getRemoteRefresh().equalsIgnoreCase("true")) {
				remoteRefresh = true;
			}
		}
		//get the user agent
		try {
			this.request = (HttpServletRequest) pageContext.getRequest();
		} catch (Exception e) {
			log.info("Exception getting request object from pageContext " + e);

		}
		if (request != null)
			UA = TagUtil.getUA(this.request);
		else
			log.info("Request is null");
		//            log.info("Ua="+UA);
		Converter MagicWand = new Converter();
		ImageWrapper image = null;
		finalImage = imageSource;
		if (imageSource == null) {
			if (remoteImage == null) {
				finalImage = remoteImage;
			}
		}
		try {

			if (!("true".equals(getRemoteImage())))
				imageSource = getImageSourcePathFromTheAppBase(request
						.getServletPath(), imageSource);
			image = MagicWand.convert(pageContext.getServletContext()
					.getRealPath("/"), imageSource, width, height, factor,
					remoteRefresh, getRemoteImage(), UA, getFormat());

			//code to fix the relative path issues..
			finalImage = image.getFileName();
			finalImage = finalImage.substring(finalImage.lastIndexOf("/") + 1);
			String dirPathName = image.getDirPathFromAppBase();
			if (dirPathName != null && !dirPathName.trim().equals("")) {
				finalImage = dirPathName + "/" + finalImage;
			}

			//this image  is already saved...

		} catch (ImageRenderingException e) {
			// TODO: handle exception
			//try to display the same image if it fits a certain thresh-hold . ..or else show some default image.. if not then some alt text.

		} catch (ImageFormatNotFound e) {
			//try logging it somewhere to ensure that its a genuine problem with the set to not render the image format .. or otherwise the wurfl.xml needs to be updated..
			log.info(" Image Format Not Found " + UA + "-->" + imageSource);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (image == null) {
			//try showing some Default image...or some alternate text
			showDefault = true;
		}

		return (EVAL_BODY_INCLUDE);

	}

	public int doEndTag() throws JspException {

		try {
			JspWriter out = pageContext.getOut();
			String imageLocation = "";
			if (showDefault) {
				if (defaultImageLocation != null
						&& !defaultImageLocation.trim().equalsIgnoreCase(""))
					imageLocation = defaultImageLocation;
				else
					imageLocation = DEFAULT_IMAGE;
			} else {

				imageLocation = finalImage;
				imageLocation = getFinalImagePath(request.getServletPath(),
						imageLocation);

			}
			if (this.alt != null && !this.alt.trim().equalsIgnoreCase(""))
				ALT = alt;

			if (imageLocation.indexOf("/") == 0) {
				imageLocation = imageLocation.replaceFirst("/", "");
				log.debug(" Image Location now is " + imageLocation);
			}

			log.debug("ImageLocation is " + imageLocation);

			out.print("<img src=\"" + imageLocation + "\" alt=\"" + ALT
					+ "\" />");
		} catch (IOException ioe) {
			throw new JspException("Error in Tag ilib: " + ioe);
		}
		return (EVAL_PAGE); // Continue with rest of JSP page
	}

	public String getFixedSize() {
		return fixedSize;
	}

	public void setFixedSize(String fixedSize) {
		this.fixedSize = fixedSize;
	}

	@Override
	public void setValueToControl(String value) {
		// TODO Auto-generated method stub
		
	}

}
